import { WechatyBuilder, ScanStatus } from 'wechaty'
import { ipcMain, app } from 'electron'
import log from '@/utils/log'
import responseJson, { sendMessageToWeb } from '@/bot/common/response'
import { deleteTempFolder } from '@/utils/file'
import qr from 'qr-image'
import { v4 as uuidV4 } from 'uuid'
import path from 'path'
import fs from 'fs'
import { getMessageDetail, createSelfMessageDetail } from '@/bot/common'
import { msgReply } from '@/bot/msg-reply'

// 是否开发环境
const isDev = import.meta.env.MODE === 'development'

/**
 * @Author: lcq
 * @Date: 2024-12-27 17:25:47
 * @brief: 微信机器人初始化
 * @return {*}
 */
function weChatBot() {
  const appUuid = isDev ? 'dev' : uuidV4() // 生成一个全局唯一的 ID
  let bot = null

  // 监听关闭事件
  app.on('before-quit', (_e) => {
    // 执行关闭前的操作
    console.log('before-quit')
    const fPath = path.resolve(process.cwd(), appUuid)
    // 开发环境下不删除登录凭证
    if (!isDev && fs.existsSync(fPath + '.memory-card.json')) {
      fs.unlinkSync(fPath + '.memory-card.json')
    }
    deleteTempFolder()
  })

  // 创建微信机器人实例
  async function createBot() {
    // 创建一个机器人
    global.bot = bot = await WechatyBuilder.build({
      name: appUuid,
      // puppet: 'wechaty-puppet-padlocal', // 如果有token，记得更换对应的puppet
      // puppet: 'wechaty-puppet-wechat', // 如果 wechaty-puppet-wechat 存在问题，也可以尝试使用上面的 wechaty-puppet-wechat4u ，记得安装
      puppet: 'wechaty-puppet-wechat4u',
      puppetOptions: {
        uos: false // 使用 uos 版本的 padlocal，需要设置为 true
        // token: 'puppet_padlocal_dc735f4c70c44615841fc7aa08a7ee8d' // padlocal token
      }
    })

    // 扫码
    bot.on('scan', onScan)
    // 登录
    bot.on('login', onLogin)
    // 登出
    bot.on('logout', onLogout)
    // 收到消息
    bot.on('message', onMessage)
    // 添加好友
    bot.on('friendship', onFriendShip)
    // 错误
    bot.on('error', onError)
  }

  async function destroyBot() {
    // 停止 Bot
    if (bot != null) await bot.stop()
    // 清除 bot 实例引用
    bot = null
  }

  // 启动微信机器人
  // eslint-disable-next-line no-unused-vars
  ipcMain.on('bot-start', () => {
    destroyBot()
      .then(async () => {
        await createBot()
        bot.start().then(() => {
          console.log('Start to log in wechat...')
          sendMessageToWeb({
            cmd: 'bot-start',
            data: responseJson('', 200, 'Start to log in wechat...')
          })
        })
      })
      .catch((err) => {
        console.error('❌ botStart error: ', err)
        sendMessageToWeb({
          cmd: 'bot-start',
          data: responseJson('', 500, '启动失败: ' + err)
        })
      })
  })

  // 扫码
  function onScan(qrcode, status) {
    if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
      const loginUrl = qrcode
      let qrcodeToPng = qr.imageSync(qrcode, { type: 'png' })
      qrcodeToPng = qrcodeToPng.toString('base64')
      const base64Img = 'data:image/png;base64,' + qrcodeToPng
      console.log('onScan:', loginUrl, ScanStatus[status], status)
      sendMessageToWeb({
        cmd: 'bot-scan',
        data: responseJson({
          qrcode: base64Img,
          loginUrl,
          status: ScanStatus[status]
        })
      })
    } else {
      // log.info('onScan: %s(%s)', ScanStatus[status], status)
      sendMessageToWeb({
        cmd: 'bot-scan',
        data: responseJson({
          status: ScanStatus[status]
        })
      })
    }
  }

  // 登录
  async function onLogin(user) {
    console.log(`<${user.name()}> has logged in`)
    const date = new Date()
    console.log(`Current time:${date}`)
    console.log(`Automatic robot chat mode has been activated`)
    sendMessageToWeb({
      cmd: 'bot-login',
      data: responseJson('', 200, `<${user.name()}>登录成功`)
    })
    createSelfMessageDetail(bot, null, `系统提示，登录成功！`)
      .then((res) => {
        res?.message?.text &&
          sendMessageToWeb({
            cmd: 'bot-message',
            data: responseJson(res)
          })
      })
      .catch((err) => {
        log.error('defaultMessage:', err)
      })
  }

  // 登出
  function onLogout(user) {
    console.log(`${user} has logged out`)
    sendMessageToWeb({
      cmd: 'bot-logout',
      data: responseJson('', 200, `<${user.name()}>退出登录`)
    })
  }

  // 收到好友请求
  async function onFriendShip(friendship) {
    log.debug('friendship', friendship)
    // {
    //   _events: {},
    //   _eventsCount: 0,
    //   id: '6258178423666130560',
    //   payload: {
    //     contactId: '@e255fc71a18dae949459aff10e145f6fd0085050b6b115026acb1238d84680a0',
    //     id: '6258178423666130560',
    //     timestamp: 1735488357,
    //     type: 1
    //   }
    // }
    try {
      const frienddShipRe = /chatgpt|chat/
      console.log(`received friend event.`)
      console.log(`received friend event from ${friendship.contact().name()}`)
      switch (friendship.type()) {
        // 1. New Friend Request
        case bot.Friendship.Type.Receive:
          if (frienddShipRe.test(friendship.hello())) {
            await friendship.accept()
          }
          break
        // 2. Friend Ship Confirmed
        case bot.Friendship.Type.Confirm:
          console.log(`friend ship confirmed`)
          break
      }
    } catch (e) {
      console.error(e)
    }
  }

  /**
   * 消息发送
   * @param msg
   * @param isSharding
   * @returns {Promise<void>}
   */
  async function onMessage(msg) {
    // 默认消息回复
    // console.log('😊😊😊收到消息', msg)
    log.debug('😊😊😊收到消息', msg)
    if (msg.type() === bot.Message.Type.Unknown) return
    await getMessageDetail(bot, msg)
      .then((res) => {
        // log.debug('😊😊😊收到消息', res)
        sendMessageToWeb({
          cmd: 'bot-message',
          data: responseJson(res)
        })
      })
      .catch((e) => {
        console.log('😊😊😊收到消息err', e.message)
      })
    // 回复消息
    msgReply(msg)
  }

  // 错误处理
  function onError(e) {
    log.error('❌ bot error handle: ', e)
    // console.log('❌ 程序退出,请重新运行程序')
    // bot.stop()
    // const msg = e?.message ? '出错了: ' + e.message : e
    // sendMessageToWeb({
    //   cmd: 'bot-error',
    //   data: responseJson('', 500, msg)
    // })
  }
}

export default weChatBot
